package com.kingsoft.miot.bridge.iam.group;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.kingsoft.miot.bridge.iam.common.AwsSignerV4Util;

/**
 * 测试组操作
 * 
 * @author HUJIANQING
 *
 */
public class TestGroupOption {

	public static void main(String[] args) {

		String api = "http://iam.api.ksyun.com/";
		StringBuffer response = new StringBuffer();
		String service = "iam";
		String region = "cn-beijing-6";

		String ak = "AKLTuJudK0klRmiH6gNWiXkFlA";
		String sk = "OBcrjHtdjbNsBB++Rl3MkdgoNQ/26jpGqkGe91PbgZeTNk7Rwbk7J1u0VGoBH5DDDg==";

		Map<String, String> parameters = new HashMap<String, String>();

		parameters.put("Action", "CreateGroup");
		parameters.put("Version", "2015-11-01");
		parameters.put("Path", "/");
		parameters.put("GroupName", "OrdinaryManager");
		parameters.put("Description", "区域管理员");
		parameters.put("AccountId", "2000090910");

		try {
			URI uri = new URI(api);
			String query = "?";
			for (Map.Entry<String, String> entry : parameters.entrySet()) {
				query = query + entry.getKey() + '=' + entry.getValue() + '&';
			}
			query = query.substring(0, query.length() - 1);
			Map<String, String> h = AwsSignerV4Util.getAuthHeaderForGet(uri, parameters, null, service, region, ak, sk);

			System.out.println(query);
			URL url = new URL(api + query);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//			conn.setConnectTimeout(10000);
			conn.setDoOutput(true);
			// By default it is GET request
			conn.setRequestMethod("GET");
			// add request header
//			conn.setRequestProperty("Accept", "application/json");
			for (Map.Entry<String, String> entry : h.entrySet()) {
				System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}
			int responseCode = conn.getResponseCode();
			System.out.println("Sending get request : " + url);
			System.out.println("Response code : " + responseCode);
			// Reading response from input Stream
			BufferedReader in;
			if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
				in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			} else {
				in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
			}
			String output;
			while ((output = in.readLine()) != null) {
				response.append(output);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// printing result from response
		System.out.println(response.toString());

	}

}
